﻿using DevExpress.Blazor;
using DevExpress.ExpressApp.Blazor.Editors;
using DevExpress.ExpressApp.Blazor.Editors.Models;
using HarmonyLib;
using System.Reflection;

namespace EasyXaf.TreeListEditors.Blazor;

public static class TreeListPatches
{
    [HarmonyPatch(typeof(DxGridAdapter))]
    [HarmonyPatch("get_GridInstance")]
    public static class DxGridAdapter_GridInstance_Patch
    {
        public static void Postfix(DxGridAdapter __instance, IGrid __result)
        {
            if (__instance is TreeListAdapter adapter)
            {
                __result = adapter.TreeList;
            }
        }
    }

    [HarmonyPatch(typeof(DxGridAdapter))]
    [HarmonyPatch("get_GridSelectionColumnModel")]
    public static class DxGridAdapter_GridSelectionColumnModel_Patch
    {
        public static void Postfix(DxGridAdapter __instance, DxGridSelectionColumnModel __result)
        {
            if (__instance is TreeListAdapter adapter)
            {
                __result = adapter.GridSelectionColumnModel;
            }
        }
    }

    [HarmonyPatch(typeof(DxGridAdapter))]
    [HarmonyPatch("get_GridDataColumnModels")]
    public static class DxGridAdapter_ColumnComponents_Patch
    {
        public static void Postfix(DxGridAdapter __instance, IEnumerable<DxGridDataColumnModel> __result)
        {
            if (__instance is TreeListAdapter adapter)
            {
                var models = (List<DxGridDataColumnModel>)typeof(DxGridAdapter)
                    .GetField("gridDataColumnModels", BindingFlags.NonPublic | BindingFlags.Instance)
                    .GetValue(adapter);

                foreach (var model in models.ToList())
                {
                    if (model is not TreeListDataColumnModel)
                    {
                        var index = models.IndexOf(model);
                        models.Remove(model);
                        models.Insert(index, TreeListDataColumnModel.Convert(model));
                    }
                }

                __result = models;
            }
        }
    }
}